import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

const service = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 从sessionStorage获取token
    const token = sessionStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 特殊处理blob响应（文件下载）
    if (response.config.responseType === 'blob') {
      return response
    }
    const res = response.data
    if (res.code !== 200) {
      ElMessage.error(res.message || 'Error')
      
      // 处理token过期或无效的情况
      if (res.code === 401) {
        // 清除sessionStorage
        sessionStorage.removeItem('token')
        sessionStorage.removeItem('userInfo')
        // 跳转到登录页
        router.push('/login')
      }
      
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
        if (res.message){ElMessage.success(res.message)}
        
      return res
    }
  },
  (error) => {
    // 处理blob类型的错误响应
    if (error.config.responseType === 'blob' && error.response.data instanceof Blob) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = () => {
          try {
            const errData = JSON.parse(reader.result as string)
            ElMessage.error(errData.message || '文件下载失败')
            reject(errData)
          } catch (e) {
            ElMessage.error('文件下载失败')
            reject(error)
          }
        }
        reader.readAsText(error.response.data)
      })
    }
    // 处理HTTP错误状态码
    if (error.response && error.response.status === 401) {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('userInfo')
      router.push('/login')
    }
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

export default service